export default {
  // 开启命名空间
  namespaced: true,
  state: {
    cart: uni.getStorageSync('cart') || [],
    selectAllFlag: false,
    // 用户信息
    userList: uni.getStorageSync('userList') || {},
    isRepeat: false,
    token: uni.getStorageSync('token') || ''
  },
  active: {

  },
  mutations: {
    getCartList(state, newperams) {
      // 判断id重复不重复
      state.isRepeat = state.cart.some(value => newperams.id === value.id)
      if (state.isRepeat) {
        // 遍历每一个
        state.cart.forEach(value => {
          // 如果重复
          if (newperams.id === value.id) {
            // 商品加1
            value.count += 1
          }
        })
      }else{
        // 如果不重复直接加进去
        state.cart.push(newperams)
      }
      uni.setStorageSync('cart', state.cart)
    },
    // 修改选中
    changeRadio(state, id) {
      state.cart.forEach((value, index) => {
        if (value.id === id) {
          value.stateFlag = !value.stateFlag
        }
      })
      uni.setStorageSync('cart', state.cart)
    },
    // 全选
    changeSelectAll(state) {
      state.cart.forEach((value) => {
        value.stateFlag = !value.stateFlag
      })
      uni.setStorageSync('cart', state.cart)
    },
    // 删除
    changeDeleteItem(state, itemId) {
      uni.showModal({
        title: '提示',
        content: '您确定要删除吗',
        success: function(res) {
          if (res.confirm) {
            state.cart = state.cart.filter((value) => {
              return value.id !== itemId
            })
            uni.setStorageSync('cart', state.cart)
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });
    },
    // 获取用户信息
    async getUserList(state) {
      const result = await uni.getUserInfo()
      let {
        nickName,
        avatarUrl
      } = result[1].userInfo
      state.userList = {
        nickName,
        avatarUrl
      }
      uni.setStorageSync('userList', state.userList)
      
    },
    editToken(state){
      state.token = uni.getStorageSync('token')
    }
  },
  getters: {
    // 全选
    all(state) {
      return state.cart.every((value) => {
        return value.stateFlag
      })
    },
    // 总价格
    totalPrice: state => {
      return state.cart.reduce((total, product) => {
        if (product.stateFlag) {
          return total + product.price * product.count;
        } else {
          return total
        }
      }, 0);
    },
    // 结算个数
    totalNumber(state) {
      return state.cart.reduce((total, product) => {
        if (product.stateFlag) {
          return total + product.count
        } else {
          return total
        }
      }, 0)
    }
  }
}